package com.eco.fishway.netty;


import com.eco.fishway.util.HexStringUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

@Slf4j
public class KndDecoder extends ByteToMessageDecoder {

    public static int BASE_LENTH = 6;

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) {
        try {
            if (in.readableBytes() >= BASE_LENTH) {
                if (in.readableBytes() > 2048) {
                    in.skipBytes(in.readableBytes());
                }
                String result = byteBuf2String(in);
                if (result == null) {
                } else {
                    out.add(result);
                }
            } else {
                in.readerIndex(in.readableBytes());
                out.add("字节长度不够(小于7)");
            }
        } catch (Exception e) {
            log.error("自定义解码器异常:{}", e.toString());
        }
    }

    private String byteBuf2String(ByteBuf byteBuf) throws Exception {
        int endReader = byteBuf.readableBytes();
        log.info("knd-tcp服务端报文长度:[{}]", Integer.valueOf(endReader));
        byte[] allData = new byte[endReader];
        byteBuf.readBytes(allData);
        String hexString = HexStringUtil.bytesToHexString(allData);
        log.info("knd-tcp服务端原始报文:{}", hexString);
        return hexString;
    }
}